package com.cgwx.controller;

import com.cgwx.Utils.result.ResultUtil;
import com.cgwx.aop.GetUserInfo;
import com.cgwx.config.BusinessException;
import com.cgwx.config.SuppressResponseLog;
import com.cgwx.entity.*;
import com.cgwx.mapper.*;
import com.cgwx.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@Api(tags = "测试")
@RequestMapping("/test")
@Slf4j
public class TestController {
    @Resource
    private IAuthorityService authorityService;
    @Resource
    private IFolderService folderService;
    @Resource
    private IRoomService roomService;
    @Resource
    private IUserService userService;
    @Resource
    private IUtilService utilService;
    @Resource
    private ISharedService sharedService;
    @Resource
    private DeptMapper deptMapper;
    @Resource
    private FolderMapper folderMapper;
    @Resource
    private TypeEntityIdMapper typeEntityIdMapper;
    @Resource
    private UserMapper userMapper;
    @Value("${deptFileManager}")
    private String deptFileManager;
    @Value("${onlyId}")
    private String onlyId;
    @Resource
    private AuthorityMapper authorityMapper;

//    private final RedissonClient redissonClient;

    private final static String LOCK = "I_AM_LOCK";

//    public TestController(RedissonClient redissonClient) {
//        this.redissonClient = redissonClient;
//    }

    @GetMapping(value = "/deleteProcess")
    @ResponseBody
    @ApiOperation("删除流程")
    public Object deleteProcess(String processInsId) {
        String resultJson;
        try {
            HttpClient httpClient = new HttpClient( );
            httpClient.getParams().setContentCharset( "UTF-8" );
            PostMethod postMethod = new PostMethod( "http://10.254.135.10:8003/flow/process/deleteProcessByProcessInsId?processInsId=" + processInsId);
            RequestEntity requestEntity = new StringRequestEntity("", "application/xml", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);
            resultJson = new String(postMethod.getResponseBody());
        } catch (Exception e) {
            log.error(e.getMessage());
            resultJson = e.getMessage();
        }
        return com.cgwx.aop.result.ResultUtil.success(resultJson);
    }

    @PostMapping(value = "/uploadMultipartFileByFileId2")
    @ResponseBody
    @ApiOperation("上传文件（带fileId）")
    public Object uploadMultipartFileByFileId2(@RequestParam String userId, @RequestParam String fileId, @RequestParam MultipartFile multipartFile) {
        String bucketName = "xgb-store";
        String path = "FileSharing";
        String clusterId = userId + "/" + utilService.getFileLocalDateTime();
        String sysSource = "PermanentAuth";
        String isMultiVersion = "1";
        String url = "http://100.100.0.10:30004/file/uploadMultipartFileByFileId2";
        if (multipartFile != null) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                HttpPost httpPost = new HttpPost(url);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
                builder.setCharset(StandardCharsets.UTF_8);
                String fileName = multipartFile.getOriginalFilename();
                builder.addBinaryBody("multipartFile", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
                builder.addTextBody("bucketName", bucketName);
                builder.addTextBody("path", path);
                builder.addTextBody("userId", userId);
                builder.addTextBody("clusterId", clusterId);
                builder.addTextBody("fileId", fileId);
                builder.addTextBody("sysSource", sysSource);
                builder.addTextBody("isMultiVersion", isMultiVersion);
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);// 执行提交
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            }
            catch (IOException e) {
                log.warn("execute failed", e);
            }
        }
        return null;
    }

    @GetMapping("/hello")
    @SuppressResponseLog
    @ApiOperation("测试打通")
    public Object hello() {
        log.info("hello123");
        return ResultUtil.success("hello");
    }
    //创建公司空间新增一条就行0 company 0 长光卫星技术股份有限公司 0
    //创建公司空间根文件夹folder_0 公司文件夹 0 root folder null null

    @GetMapping("/createRoom")
    @ApiOperation("创建所有用户和部门的空间")
    @Transactional
    public Object createRoom() {
        Room room = new Room();
        room.setUsedSpace(0);
        room.setId(roomService.generateId());
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        room.setCreateTime(time);
        room.setUpdateTime(time);
        List<UsUser> users = userService.getAllUser();
        for(UsUser user: users){
            room.setRoomId(user.getAccount());
            room.setRoomName(user.getName());
            room.setRoomType("staff");
            List<Room> rooms = roomService.getRoom(room);
            if(!rooms.isEmpty()) {
                log.warn("{}已存在!", user.getName());
                continue;
            }
            if(roomService.insertStaffRoom(room).equals("新增失败!")) log.warn("员工{}新增失败!", user.getName());
        }
        List<UsDept> depts = deptMapper.getAllDept();
        for(UsDept dept: depts){
            room.setRoomId(dept.getOrganizationId());
            room.setRoomName(dept.getOrganizationName());
            room.setRoomType("dept");
            List<Room> rooms = roomService.getRoom(room);
            if(!rooms.isEmpty()){
                log.warn("{}已存在!", dept.getOrganizationName());
                continue;
            }
            if(roomService.insertDeptRoom(room).equals("新增失败!")) log.warn("部门{}新增失败!", dept.getOrganizationName());
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/createRoot")
    @ApiOperation("创建所有用户和部门的文件夹根")
    @Transactional
    public Object createRoot() {
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Folder folder = new Folder();
        folder.setParentId("root");
        folder.setCreateTime(time);
        folder.setType("folder");
        List<UsUser> users = userService.getAllUser();
        for(UsUser user: users){
            String roomId = roomService.getPersonalRoom(user.getAccount());
            folder.setOwnerAccount(user.getAccount());
            folder.setOwnerName(user.getName());
            folder.setEntityRoom(roomId);
            folder.setEntityName("我的文件夹");
            folder.setEntityId(folderService.generateEntityId());
            boolean result = folderMapper.insertFolder(folder);
            if(!result) throw new BusinessException("用户文件夹新增失败!");
        }
        folder.setType("dept");
        List<UsDept> depts = deptMapper.getAllDept();
        Room room = new Room();
        room.setRoomType("dept");
        folder.setOwnerAccount(null);
        folder.setOwnerName(null);
        for(UsDept dept: depts){
            room.setRoomId(dept.getOrganizationId());
            String roomId = roomService.getRoom(room).get(0).getId();
            folder.setEntityRoom(roomId);//部门id
            folder.setEntityId(folderService.generateEntityId());
            folder.setEntityName(dept.getOrganizationName());
            boolean result = folderMapper.insertFolder(folder);
            if(!result) throw new BusinessException("部门文件夹新增失败!");
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/createPersonalFolder")
    @ApiOperation("创建所有用户创建外部传输文件夹")
    @Transactional
    public Object createPersonalFolder() {
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        List<UsUser> users = userService.getAllUser();
        for(UsUser user: users) {
            Folder folder = new Folder();
            folder.setType("folder");
            String roomId = roomService.getPersonalRoom(user.getAccount());
            folder.setOwnerAccount(user.getAccount());
            folder.setOwnerName(user.getName());
            folder.setEntityRoom(roomId);
            Folder folderSearch = new Folder();
            folderSearch.setParentId("root");
            folderSearch.setEntityRoom(roomId);
            folderSearch.setEntityName("我的文件夹");
            List<Folder> folders = folderService.getFolder(folderSearch);
            if(folders == null || folders.size() != 1) {
                System.out.println(folders);
                continue;
            }
            folder.setParentId(folders.get(0).getEntityId());
            folder.setEntityName("外部传输文件夹");
            if(folderMapper.getFolder(folder).isEmpty()){
                folder.setEntityId(folderService.generateEntityId());
                folder.setCreateTime(time);
                boolean result = folderMapper.insertFolder(folder);
                if (!result) throw new BusinessException("用户外部传输文件夹新增失败!");
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/createRootAuthority")
    @ApiOperation("创建公司和部门的文件夹根权限")
    @Transactional
    public Object createRootAuthority() {
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("company");
        authority.setFileOrFolder("folder");
        authority.setEntityId("folder_0");//根据情况改
        authority.setEntityName("公司文件夹");//根据情况改
        authority.setPermissionId("0");
        authority.setPermissionName("长光卫星技术股份有限公司");
        authority.setAuthorityLevel("2");
        authority.setId(authorityService.generateId());
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        //公司权限
        boolean result = authorityService.insertAuthority(authority);
        if(!result) throw new BusinessException("公司根权限新增失败!");

        authority.setPermissionType("dept");
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        authority.setAuthorityLevel("3");
        //部门权限
        List<UsDept> depts = deptMapper.getAllDept();
        for(UsDept dept: depts){
            Folder folder = new Folder();
            folder.setEntityName(dept.getOrganizationName());
            folder.setParentId("root");
            List<Folder> folderFinds = folderService.getFolder(folder);
            if(folderFinds.isEmpty()){
                log.error("createRootAuthority: {}根文件夹不存在!", dept.getOrganizationId());
                throw new BusinessException(dept.getOrganizationId() + "根文件夹不存在!");
            }
            if(folderFinds.size() > 1){
                log.error("createRootAuthority: {}根文件夹不唯一!", dept.getOrganizationId());
                throw new BusinessException(dept.getOrganizationId() + "根文件夹不唯一!");
            }
            String entityId = folderFinds.get(0).getEntityId();
            authority.setEntityId(entityId);
            authority.setEntityName(dept.getOrganizationName());
            authority.setPermissionId(dept.getOrganizationId());
            authority.setPermissionName(dept.getOrganizationName());
            authority.setId(authorityService.generateId());
            result = authorityService.insertAuthority(authority);
            if(!result){
                log.error("部门根权限新增失败!");
                throw new BusinessException("部门根权限新增失败!");
            }
        }
        return ResultUtil.success("true");
    }



    @GetMapping("/insertNewStaff")
    @ApiOperation("定期巡检，增加新员工的空间")
    @Scheduled(cron ="0 0 20 * * ?")
    @Transactional
    public void insertNewStaff() throws InterruptedException {
//        RLock rLock = redissonClient.getLock(LOCK);
//        rLock.lock();
        try {
            Timestamp time = Timestamp.valueOf(LocalDateTime.now());
            List<UsUser> users = userService.getAllUser();
            Folder folder = new Folder();
            folder.setCreateTime(time);
            folder.setType("folder");
            for(UsUser user: users){
                Room room = new Room();
                room.setId(null);
                room.setRoomId(user.getAccount());
                room.setRoomName(user.getName());
                if(room.getRoomName() == null) room.setRoomName(user.getAccount());
                room.setRoomType("staff");
                List<Room> rooms = roomService.getRoom(room);
                if(user.getAccount().equals(onlyId)) log.info(user.toString());
                if(rooms.isEmpty()) {
                    //创建个人空间
                    log.info("新增员工{}_{}", user.getName(), user.getAccount());
                    if(roomService.insertStaffRoom(room).equals("新增失败!")){
                        log.error("insertNewStaff: 员工{}新增失败!", user.getName());
                        throw new BusinessException("insertNewStaff: 员工" + user.getName() + "新增失败!");
                    }
                    room =roomService.getRoom(room).get(0);
                    //创建个人空间根文件夹
                    folder.setParentId("root");
                    folder.setOwnerAccount(user.getAccount());
                    folder.setOwnerName(user.getName());
                    folder.setEntityRoom(room.getId());
                    folder.setEntityName("我的文件夹");
                    folder.setEntityId(folderService.generateEntityId());
                    boolean result = folderMapper.insertFolder(folder);
                    if(!result){
                        log.error("用户文件夹新增失败!");
                        throw new BusinessException("用户文件夹新增失败!");
                    }
                    folder.setParentId(folder.getEntityId());
                    folder.setEntityName("外部传输文件夹");
                    if(folderMapper.getFolder(folder).isEmpty()){
                        folder.setEntityId(folderService.generateEntityId());
                        result = folderMapper.insertFolder(folder);
                        if (!result) throw new BusinessException("用户外部传输文件夹新增失败!");
                    }
                }
            }
        }
        catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
//            rLock.unlock();
        }
    }

    @GetMapping("/insertNewStaffFolder")
    @ApiOperation("定期巡检，增加新员工的文件夹")
    @Scheduled(cron ="0 5 20 * * ?")
    @Transactional
    public void insertNewStaffFolder() {
//        RLock rLock = redissonClient.getLock(LOCK);
//        rLock.lock();
        try {
            Timestamp time = Timestamp.valueOf(LocalDateTime.now());
            List<UsUser> users = userService.getAllUser();
            for(UsUser user: users){
                Room room = new Room();
                room.setRoomId(user.getAccount());
                room.setRoomType("staff");
                List<Room> rooms = roomService.getRoom(room);
                if(user.getAccount().equals(onlyId)) log.info(user.toString());
                if(!rooms.isEmpty()) {
                    Folder folder = new Folder();
                    folder.setCreateTime(time);
                    folder.setType("folder");
                    folder.setOwnerAccount(user.getAccount());
                    folder.setEntityName("我的文件夹");
                    if(folderMapper.getFolder(folder).isEmpty()){
                        log.info("{}新增文件夹", user.getName());
                        folder.setEntityRoom(rooms.get(0).getId());
                        folder.setParentId("root");
                        folder.setOwnerName(user.getName());
                        folder.setEntityId(folderService.generateEntityId());
                        boolean result = folderMapper.insertFolder(folder);
                        if(!result){
                            log.error("用户文件夹新增失败!");
                            throw new BusinessException("用户文件夹新增失败!");
                        }
                        folder.setParentId(folder.getEntityId());
                        folder.setEntityName("外部传输文件夹");
                        if(folderMapper.getFolder(folder).isEmpty()){
                            folder.setEntityId(folderService.generateEntityId());
                            result = folderMapper.insertFolder(folder);
                            if (!result) throw new BusinessException("用户外部传输文件夹新增失败!");
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            log.warn(e.getMessage());
        } finally {
//            rLock.unlock();
        }
    }

    @GetMapping("/insertNewDept")
    @ApiOperation("定期巡检，增加新部门的空间")
    @Scheduled(cron ="0 5 20 * * ?")
    @Transactional
    public void insertNewDept() throws InterruptedException {
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        List<UsDept> depts = deptMapper.getAllDept();
        Folder folder = new Folder();
        folder.setType("dept");
        folder.setCreateTime(time);
        folder.setParentId("root");
        log.info("所有部门: {}", depts.toString());
        for (UsDept dept : depts) {
            Room room = new Room();
            room.setUpdateTime(time);
            room.setCreateTime(time);
            room.setId(null);
            room.setRoomId(dept.getOrganizationId());
            room.setRoomName(dept.getOrganizationName());
            room.setRoomType("dept");
            List<Room> rooms = roomService.getRoom(room);
            //if(dept.getOrganizationName().equals("光机结构第一研究室")) log.info(String.valueOf(room));
            //if(dept.getOrganizationName().equals("光机结构第二研究室")) log.info(String.valueOf(room));
            if (rooms.isEmpty()) {
                //创建部门的空间根文件夹
                log.info("新增部门{}_{}", dept.getOrganizationName(), dept.getOrganizationId());
                room.setUsedSpace(0);
                if(roomService.insertDeptRoom(room).equals("新增失败!")){
                    log.error("insertNewDept: 部门{}新增失败!", dept.getOrganizationName());
                    throw new BusinessException("insertNewDept: 部门" + dept.getOrganizationName() + "新增失败!");
                }
                log.info("新增111:{}", room);
                Thread.sleep(1000);
                //创建部门的空间根文件夹
                log.info("新增222:{}", room);
                String roomId = roomService.getRoom(room).get(0).getId();
                log.info("新增333:{}", room);
                folder.setEntityRoom(roomId);
                folder.setEntityName(dept.getOrganizationName());
                folder.setEntityId(folderService.generateEntityId());
                log.info("新增文件夹:{}", folder);
                boolean result = folderMapper.insertFolder(folder);
                if (!result){
                    log.error("部门文件夹新增失败!");
                    throw new BusinessException("部门文件夹新增失败!");
                }
                Thread.sleep(1000);
                //创建部门权限
                Authority authority = new Authority();
                authority.setPermissionType("dept");
                authority.setCreateTime(time);
                authority.setUpdateTime(time);
                authority.setAuthorityLevel("3");
                Folder folder0 = new Folder();
                folder0.setEntityName(dept.getOrganizationName());
                List<Folder> folderFinds = folderService.getFolder(folder0);
                if (folderFinds.isEmpty()){
                    log.error("insertNewDept: {}根文件夹不存在!", dept.getOrganizationId());
                    throw new BusinessException(dept.getOrganizationId() + "根文件夹不存在!");
                }
                if (folderFinds.size() > 1){
                    log.error("{}根文件夹不唯一!", dept.getOrganizationId());
                    throw new BusinessException(dept.getOrganizationId() + "根文件夹不唯一!");
                }
                String entityId = folderFinds.get(0).getEntityId();
                authority.setEntityId(entityId);
                authority.setEntityName(dept.getOrganizationName());
                authority.setPermissionId(dept.getOrganizationId());
                authority.setPermissionName(dept.getOrganizationName());
                authority.setId(authorityService.generateId());
                if(!authorityService.insertAuthority(authority)){
                    log.error("insertNewDept: 部门权限{}新增失败!", dept.getOrganizationName());
                    throw new BusinessException("insertNewDept: 部门权限" + dept.getOrganizationName() + "新增失败!");
                }
            }
        }
    }

    @GetMapping("/insertManager")
    @ApiOperation("新增公司文件夹管理员（公司空间）")
    @Transactional
    public Object insertManager(@RequestParam String account) {
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userService.getUser(user).get(0);
        String name = user.getName();
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        authority.setPermissionId(account);
        authority.setPermissionName(name);
        List<String> entityIds = authorityService.getChildrenAndMyself("folder_0");
        for(String entityId : entityIds){
            authority.setEntityId(entityId);//部门文件夹
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result){
                log.error("公司权限新增失败!");
                throw new BusinessException("公司权限新增失败!");
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/insertDeptManager")
    @ApiOperation("新增部门文件夹管理员（部门文件）")
    @Transactional
    public Object insertDeptManager(@RequestParam String account) {
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userService.getUser(user).get(0);
        String name = user.getName();
        String deptId = user.getDeptId();
        UsDept dept = new UsDept();
        dept.setOrganizationId(deptId);
        dept = deptMapper.getDept(dept);
        if(dept == null) return null;
        String deptName = dept.getOrganizationName();
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        Folder folder = new Folder();
        folder.setEntityName(deptName);
        folder.setParentId("root");
        List<Folder> folderFinds = folderService.getFolder(folder);
        if(folderFinds.isEmpty()){
            log.warn("insertDeptManager{}根文件夹不存在!", deptName);
            return null;
        }
        if(folderFinds.size() > 1) log.warn("insertDeptManager{}根文件夹不唯一!", deptName);
        authority.setPermissionId(account);
        authority.setPermissionName(name);
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        String entityId = folderFinds.get(0).getEntityId();
        List<String> entityIds = authorityService.getChildrenAndMyself(entityId);
        for(String entityId2 : entityIds){
            authority.setEntityId(entityId2);//部门文件夹
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId2));//部门文件夹
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result){
                log.error("员工部门权限新增失败!");
                throw new BusinessException("部门根权限新增失败!");
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/insertFolder")
    @ApiOperation("新建文件夹")
    @Transactional
    public Object insertFolder(@RequestParam String entityName, @RequestParam String parentId) throws InterruptedException {
        Folder folder = new Folder();
        folder.setEntityId(parentId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        String result = folderService.insertFolder("", "", "", roomId, entityName, parentId, "staff");
        folder = new Folder();
        folder.setParentId(parentId);
        folder.setEntityName(entityName);
        Thread.sleep(200);
        folder = folderService.getFolder(folder).get(0);
        if(folder == null) return null;
        if(result.equals("新增成功!")) return folder.getEntityId();
        return null;
    }

    //先建内部控制文件
    //再建其他大类小类
    @GetMapping(value = "/initTypeEntityId")
    @ResponseBody
    @ApiOperation("文件类别对应路径初始化(内部控制文件)")
    @Transactional
    public Object initTypeEntityId(String outer, String inner, String level, String parentId) throws InterruptedException {
        //先生成文件夹
        String signType = "内部控制文件";
        String path = "公司文件/" + signType + "/" + outer + "/" + inner + "/";
        List<UsDept> depts = deptMapper.getAllDept();
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setLevel(level);
        typeEntityId.setFileOuterType(outer);
        typeEntityId.setFileInnerType(inner);
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("company");
        authority.setFileOrFolder("folder");
        authority.setPermissionId("0");
        authority.setPermissionName("长光卫星技术股份有限公司");
        authority.setAuthorityLevel("2");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        for(UsDept dept: depts){
            if(!dept.getOrganizationName().equals("经营班子")){
                typeEntityId.setId(UUID.randomUUID().toString());
                typeEntityId.setDeptId(dept.getOrganizationId());
                typeEntityId.setDeptName(dept.getOrganizationName());
                typeEntityId.setPath(path + dept.getOrganizationName());
                //文件共享平台建文件夹
                String entityId = (String) insertFolder(dept.getOrganizationName(), parentId);
                typeEntityId.setEntityId(entityId);
                if(entityId == null) return ResultUtil.success("false");
                typeEntityIdMapper.insertTypeEntityId(typeEntityId);
                //新增公司权限
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("公司根权限新增失败!");
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityIdByDept")
    @ResponseBody
    @ApiOperation("部门文件类别对应路径初始化(内部控制文件)")
    @Transactional
    public Object initTypeEntityIdByDept(String outer, String inner, String level, String parentId, String deptName) throws InterruptedException {
        //先生成文件夹
        String signType = "内部控制文件";
        String path = "公司文件/" + signType + "/" + outer + "/" + inner + "/";
        UsDept dept = new UsDept();
        dept.setOrganizationName(deptName);
        dept = deptMapper.getDept(dept);
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setLevel(level);
        typeEntityId.setFileOuterType(outer);
        typeEntityId.setFileInnerType(inner);
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("company");
        authority.setFileOrFolder("folder");
        authority.setPermissionId("0");
        authority.setPermissionName("长光卫星技术股份有限公司");
        authority.setAuthorityLevel("2");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        if(!dept.getOrganizationName().equals("经营班子")){
            typeEntityId.setId(UUID.randomUUID().toString());
            typeEntityId.setDeptId(dept.getOrganizationId());
            typeEntityId.setDeptName(dept.getOrganizationName());
            typeEntityId.setPath(path + dept.getOrganizationName());
            //文件共享平台建文件夹
            String entityId = (String) insertFolder(dept.getOrganizationName(), parentId);
            typeEntityId.setEntityId(entityId);
            if(entityId == null) return ResultUtil.success("false");
            typeEntityIdMapper.insertTypeEntityId(typeEntityId);
            //新增公司权限
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("公司根权限新增失败!");
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId2")
    @ResponseBody
    @ApiOperation("文件类别对应路径初始化(非项目报告文件)")
    @Transactional
    public Object initTypeEntityId2(String name, String level) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/报告类文件/" + name;
        List<UsDept> depts = deptMapper.getAllDept();
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(name);
        typeEntityId.setFileOuterType(name);
        typeEntityId.setLevel(level);
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        for(UsDept dept: depts){
            if(!dept.getOrganizationName().equals("经营班子")){
                typeEntityId.setId(UUID.randomUUID().toString());
                typeEntityId.setDeptId(dept.getOrganizationId());
                typeEntityId.setDeptName(dept.getOrganizationName());
                typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
                //文件共享平台建文件夹
                Folder folder = new Folder();
                folder.setEntityName(dept.getOrganizationName());
                folder.setParentId("root");
                List<Folder> folders = folderMapper.getFolder(folder);
                //tag
                if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
                else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
                authority.setPermissionName(dept.getOrganizationName());
                authority.setPermissionId(dept.getOrganizationId());

                String entityId = (String) insertFolder(dept.getOrganizationName() + "签批文件", folders.get(0).getEntityId());
                if(entityId == null) return ResultUtil.success("false");
                //tag
                folder = new Folder();
                folder.setEntityId(entityId);
                folder.setTag("签批文件");
                folderService.updateFolderById(folder);

                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");

                entityId = (String) insertFolder("报告类文件", entityId);
                if(entityId == null) return ResultUtil.success("false");
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");

                entityId = (String) insertFolder(name, entityId);
                if(entityId == null) return ResultUtil.success("false");
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");
                typeEntityId.setEntityId(entityId);
                typeEntityIdMapper.insertTypeEntityId(typeEntityId);
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId2BydDept")
    @ResponseBody
    @ApiOperation("文件类别对应路径初始化(非项目报告文件)")
    @Transactional
    public Object initTypeEntityId2BydDept(String name, String level, String deptName) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/报告类文件/" + name;
        UsDept dept = new UsDept();
        dept.setOrganizationName(deptName);
        dept = deptMapper.getDept(dept);
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(name);
        typeEntityId.setFileOuterType(name);
        typeEntityId.setLevel(level);
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        if(!dept.getOrganizationName().equals("经营班子")){
            typeEntityId.setId(UUID.randomUUID().toString());
            typeEntityId.setDeptId(dept.getOrganizationId());
            typeEntityId.setDeptName(dept.getOrganizationName());
            typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
            //文件共享平台建文件夹
            Folder folder = new Folder();
            folder.setEntityName(dept.getOrganizationName());
            folder.setParentId("root");
            List<Folder> folders = folderMapper.getFolder(folder);
            //tag
            if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
            else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
            authority.setPermissionName(dept.getOrganizationName());
            authority.setPermissionId(dept.getOrganizationId());

            String entityId = (String) insertFolder(dept.getOrganizationName() + "签批文件", folders.get(0).getEntityId());
            if(entityId == null) return ResultUtil.success("false");
            //tag
            folder = new Folder();
            folder.setEntityId(entityId);
            folder.setTag("签批文件");
            folderService.updateFolderById(folder);

            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");

            entityId = (String) insertFolder("报告类文件", entityId);
            if(entityId == null) return ResultUtil.success("false");
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");

            entityId = (String) insertFolder(name, entityId);
            if(entityId == null) return ResultUtil.success("false");
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");
            typeEntityId.setEntityId(entityId);
            typeEntityIdMapper.insertTypeEntityId(typeEntityId);
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId3")
    @ResponseBody
    @ApiOperation("报告类路径新增(非项目报告文件，已经存在报告类文件夹的情况下)")
    @Transactional
    public Object initTypeEntityId3(String name) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/报告类文件/" + name;
        List<UsDept> depts = deptMapper.getAllDept();
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(name);
        typeEntityId.setFileOuterType(name);
        typeEntityId.setLevel("0");
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        for(UsDept dept: depts){
            if(!dept.getOrganizationName().equals("经营班子")){
                typeEntityId.setId(UUID.randomUUID().toString());
                typeEntityId.setDeptId(dept.getOrganizationId());
                typeEntityId.setDeptName(dept.getOrganizationName());
                typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
                //文件共享平台建文件夹
                Room room = new Room();
                room.setRoomType("dept");
                room.setRoomName(dept.getOrganizationName());
                List<Room> rooms = roomService.getRoom(room);
                if(rooms.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
                else if(rooms.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
                room = rooms.get(0);

                Folder folder = new Folder();
                folder.setEntityName("报告类文件");
                folder.setEntityRoom(room.getId());
                List<Folder> folders = folderMapper.getFolder(folder);
                log.info(dept.getOrganizationName());
                log.info(folders.toString());
                //tag
                if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
                else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
                authority.setPermissionName(dept.getOrganizationName());
                authority.setPermissionId(dept.getOrganizationId());

                String entityId = (String) insertFolder(name, folders.get(0).getEntityId());
                log.info(entityId);
                if(entityId == null) return ResultUtil.success("false");
                //tag
                folder = new Folder();
                folder.setEntityId(entityId);
                folder.setTag("签批文件");
                folderService.updateFolderById(folder);
                log.info(String.valueOf(folder));
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");
                log.info(String.valueOf(authority));
                typeEntityId.setEntityId(entityId);
                typeEntityIdMapper.insertTypeEntityId(typeEntityId);
                log.info(String.valueOf(typeEntityId));
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId3ByDept")
    @ResponseBody
    @ApiOperation("报告类路径新增(非项目报告文件，已经存在报告类文件夹的情况下)")
    @Transactional
    public Object initTypeEntityId3ByDept(String name, String deptName) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/报告类文件/" + name;
        UsDept dept = new UsDept();
        dept.setOrganizationName(deptName);
        dept = deptMapper.getDept(dept);
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(name);
        typeEntityId.setFileOuterType(name);
        typeEntityId.setLevel("0");
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        if(!dept.getOrganizationName().equals("经营班子")){
            typeEntityId.setId(UUID.randomUUID().toString());
            typeEntityId.setDeptId(dept.getOrganizationId());
            typeEntityId.setDeptName(dept.getOrganizationName());
            typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
            //文件共享平台建文件夹
            Room room = new Room();
            room.setRoomType("dept");
            room.setRoomName(dept.getOrganizationName());
            List<Room> rooms = roomService.getRoom(room);
            if(rooms.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
            else if(rooms.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
            room = rooms.get(0);

            Folder folder = new Folder();
            folder.setEntityName("报告类文件");
            folder.setEntityRoom(room.getId());
            List<Folder> folders = folderMapper.getFolder(folder);
            log.info(dept.getOrganizationName());
            log.info(folders.toString());
            //tag
            if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
            else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
            authority.setPermissionName(dept.getOrganizationName());
            authority.setPermissionId(dept.getOrganizationId());

            String entityId = (String) insertFolder(name, folders.get(0).getEntityId());
            log.info(entityId);
            if(entityId == null) return ResultUtil.success("false");
            //tag
            folder = new Folder();
            folder.setEntityId(entityId);
            folder.setTag("签批文件");
            folderService.updateFolderById(folder);
            log.info(String.valueOf(folder));
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");
            log.info(String.valueOf(authority));
            typeEntityId.setEntityId(entityId);
            typeEntityIdMapper.insertTypeEntityId(typeEntityId);
            log.info(String.valueOf(typeEntityId));
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId4")
    @ResponseBody
    @ApiOperation("文件类别对应路径初始化(非项目图册文件)")
    @Transactional
    public Object initTypeEntityId4(String type, String name) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/图册类文件/" + name;
        List<UsDept> depts = deptMapper.getAllDept();
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(type);
        typeEntityId.setFileOuterType(type);
        typeEntityId.setLevel("0");
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        for(UsDept dept: depts){
            if(!dept.getOrganizationName().equals("经营班子")){
                System.out.println(dept);
                typeEntityId.setId(UUID.randomUUID().toString());
                typeEntityId.setDeptId(dept.getOrganizationId());
                typeEntityId.setDeptName(dept.getOrganizationName());
                typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
                //文件共享平台建文件夹
                Folder folder = new Folder();
                folder.setEntityName(dept.getOrganizationName() + "签批文件");
                folder.setTag("签批文件");
                List<Folder> folders = folderMapper.getFolder(folder);
                //tag
                if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
                else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
                authority.setPermissionName(dept.getOrganizationName());
                authority.setPermissionId(dept.getOrganizationId());

                String entityId = (String) insertFolder(type, folders.get(0).getEntityId());
                if(entityId == null) return ResultUtil.success("false");
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");

                entityId = (String) insertFolder(name, entityId);
                if(entityId == null) return ResultUtil.success("false");
                authority.setEntityId(entityId);//根据情况改
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                authority.setId(authorityService.generateId());
                result = authorityService.insertAuthority(authority);
                if(!result) throw new BusinessException("部门签批权限新增失败!");
                typeEntityId.setEntityId(entityId);
                typeEntityIdMapper.insertTypeEntityId(typeEntityId);
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTypeEntityId4ByDept")
    @ResponseBody
    @ApiOperation("文件类别对应路径初始化(非项目图册文件)")
    @Transactional
    public Object initTypeEntityId4ByDept(String type, String deptName) throws InterruptedException {
        String signType = "非项目报告文件";
        String path = "签批文件/图册类文件/" + type;
        UsDept dept = new UsDept();
        dept.setOrganizationName(deptName);
        dept = deptMapper.getDept(dept);
        TypeEntityId typeEntityId = new TypeEntityId();
        typeEntityId.setType(type);
        typeEntityId.setFileOuterType("图册类文件");
        typeEntityId.setLevel("0");
        typeEntityId.setSignType(signType);
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("3");
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        if(!dept.getOrganizationName().equals("经营班子")){
            System.out.println(dept);
            typeEntityId.setId(UUID.randomUUID().toString());
            typeEntityId.setDeptId(dept.getOrganizationId());
            typeEntityId.setDeptName(dept.getOrganizationName());
            typeEntityId.setPath(dept.getOrganizationName() + "/" + dept.getOrganizationName() + path);
            //文件共享平台建文件夹
            Folder folder = new Folder();
            folder.setEntityName(dept.getOrganizationName() + "签批文件");
            folder.setTag("签批文件");
            List<Folder> folders = folderMapper.getFolder(folder);
            //tag
            if(folders.size() > 1) throw new BusinessException(dept.getOrganizationName() + ">1!");
            else if(folders.isEmpty()) throw new BusinessException(dept.getOrganizationName() + "=0!");
            authority.setPermissionName(dept.getOrganizationName());
            authority.setPermissionId(dept.getOrganizationId());

            String entityId = (String) insertFolder("图册类文件", folders.get(0).getEntityId());
            if(entityId == null) return ResultUtil.success("false");
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            boolean result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");

            entityId = (String) insertFolder(type, entityId);
            if(entityId == null) return ResultUtil.success("false");
            authority.setEntityId(entityId);//根据情况改
            authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
            authority.setId(authorityService.generateId());
            result = authorityService.insertAuthority(authority);
            if(!result) throw new BusinessException("部门签批权限新增失败!");
            typeEntityId.setEntityId(entityId);
            typeEntityIdMapper.insertTypeEntityId(typeEntityId);
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/initTagFolder")
    @ResponseBody
    @ApiOperation("新建签批文件文件夹")
    @Transactional
    public Object initTagFolder(String name, String deptName, String parentId, String auth) throws InterruptedException {
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setPermissionType("dept");
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel(auth);
        authority.setUpdateTime(time);
        authority.setCreateTime(time);

        UsDept dept = new UsDept();
        dept.setOrganizationName(deptName);
        dept = deptMapper.getDept(dept);
        authority.setPermissionName(deptName);
        authority.setPermissionId(dept.getOrganizationId());

        String entityId = (String) insertFolder(name, parentId);
        if(entityId == null) return ResultUtil.success("false");
        //tag
        Folder folder = new Folder();
        folder.setEntityId(entityId);
        folder.setTag("签批文件");
        folderService.updateFolderById(folder);

        authority.setEntityId(entityId);//根据情况改
        authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
        authority.setId(authorityService.generateId());
        boolean result = authorityService.insertAuthority(authority);
        if(!result) throw new BusinessException("文件夹权限新增失败!");
        return ResultUtil.success("true");
    }

    @GetMapping("/insertDeptManagerDefault")
    @ApiOperation("将部门正副职和部门签批文件管理员加入部门文件夹管理员和公司内控中相应部门的管理员")
    @Transactional
    public Object insertDeptManagerDefault() {
        List<UsUser> users = userService.getAllUser();
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        for (UsUser user : users) {
            if((utilService.isDeptLeader(user.getAccount()) && !user.getDeptId().equals("000100")) || user.getRoleId().contains("20240906_21002_role")){
                //新增部门空间权限
                insertDeptManager(user.getAccount());
                //新增公司内控中相应部门的管理员
                Folder folder = new Folder();
                folder.setEntityName(user.getDeptName());
                folder.setEntityRoom("0");
                authority.setPermissionId(user.getAccount());
                authority.setPermissionName(user.getName());
                List<Folder> folders = folderMapper.getFolder(folder);
                for (Folder folder1 : folders) {
                    authority.setId(authorityService.generateId());
                    authority.setEntityId(folder1.getEntityId());
                    authority.setEntityName(folder1.getEntityName());
                    authorityService.insertAuthority(authority);
                }
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping("/insertDeptManagerDefault2")
    @ApiOperation("将部门正副职和部门签批文件管理员加入部门文件夹管理员")
    @Transactional
    public Object insertDeptManagerDefault2() {
        List<UsUser> users = userService.getAllUser();
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority = new Authority();
        authority.setFileOrFolder("folder");
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        for (UsUser user : users) {
            if((utilService.isDeptLeader(user.getAccount()) && !user.getDeptId().equals("000100")) || user.getRoleId().contains("20240906_21002_role")){
                //新增部门空间权限
                insertDeptManager(user.getAccount());
            }
        }
        return ResultUtil.success("true");
    }

    @GetMapping(value = "/deptReportLeader")
    @ResponseBody
    @ApiOperation("部门报告文件映射（分配副总权限）")
    @Transactional
    public Object deptReportLeader() {
        StringBuilder sharedIdsBuilder = new StringBuilder();
        StringBuilder entityIdsBuilder = new StringBuilder();
        List<UsUser> users = userService.getAllUser();
        for(UsUser user: users){
            if(user.getDeptId().equals("000100")) sharedIdsBuilder.append(user.getAccount()).append(",");
        }
        String sharedIds = sharedIdsBuilder.substring(0, sharedIdsBuilder.length() - 1);
        List<UsDept> depts = deptMapper.getAllDept();
        for(UsDept dept: depts) {
            Folder folder = new Folder();
            folder.setEntityName(dept.getOrganizationName() + "签批文件");
            List<Folder> folderFinds = folderService.getFolder(folder);
            if (folderFinds.isEmpty()) {
                log.error("deptReportLeader: {}根文件夹不存在!", dept.getOrganizationId());
                throw new BusinessException(dept.getOrganizationId() + "根文件夹不存在!");
            }
            if (folderFinds.size() > 1) {
                log.error("deptReportLeader: {}根文件夹不唯一!", dept.getOrganizationId());
                throw new BusinessException(dept.getOrganizationId() + "根文件夹不唯一!");
            }
            entityIdsBuilder.append(folderFinds.get(0).getEntityId()).append(",");
        }
        String entityIds = entityIdsBuilder.substring(0, entityIdsBuilder.length() - 1);
        System.out.println(sharedIds);
        System.out.println(entityIds);
        return ResultUtil.success(insertDeptShared(entityIds, sharedIds));
    }

    @GetMapping("/insertDeptShared")
    @GetUserInfo
    @Transactional
    @ApiOperation("分享部门签批文件夹")
    public Object insertDeptShared(String entityIds, String sharedIds) {
        String[] entityIdList = entityIds.split(",");
        String[] sharedIdList = sharedIds.split(",");
        Shared shared = new Shared();
        shared.setAccount("0");
        shared.setIsDeptReport("true");
        String result;
        for(String sharedId: sharedIdList){
            shared.setSharedId(sharedId);
            for(String entityId: entityIdList){
                shared.setEntityId(entityId);
                result = sharedService.insertShared(shared);
                if(!result.equals("分享成功!")) throw new BusinessException("分享失败!");
            }
        }
        return ResultUtil.success("分享成功!");
    }

    @GetMapping("/insertDeptLeaderCompanyFolderAuth")
    @GetUserInfo
    @Transactional
    @ApiOperation("给部门正副职和管理员分配公司对应签批文件夹权限")
    public Object insertDeptLeaderCompanyFolderAuth() {
        Authority authority = new Authority();
        authority.setAuthorityLevel("4");
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        authority.setUpdateTime(time);
        authority.setCreateTime(time);
        authority.setPermissionType("staff");
        Folder folderSelect = new Folder();
        folderSelect.setTag("签批文件");
        List<UsUser> users = userMapper.getAllUser();
        for(UsUser user: users){
            if(!utilService.isDeptLeader(user.getAccount()) && !user.getRoleId().contains(deptFileManager)) continue;
            folderSelect.setEntityName(user.getDeptName());
            List<Folder> folders = folderMapper.getFolder(folderSelect);
            for(Folder folder : folders){
                List<String> entities = authorityService.getChildrenAndMyself(folder.getEntityId());
                for(String entityId: entities){
                    authority.setId(authorityService.generateId());
                    authority.setPermissionId(user.getAccount());
                    authority.setPermissionName(user.getName());
                    authority.setEntityId(entityId);
                    authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                    if(entityId.startsWith("folder")) authority.setFileOrFolder("folder");
                    else authority.setFileOrFolder("file");
                    if(!authorityMapper.insertAuthority(authority)){
                        log.error("insertDeptLeaderCompanyFolderAuth: 员工文件夹权限新增失败!");
                        throw new BusinessException("insertDeptLeaderCompanyFolderAuth: 员工文件夹权限新增失败!");
                    }
                }
            }
        }
        return ResultUtil.success("部门正副职和管理员分配公司对应签批文件夹权限成功!");
    }

    @GetMapping("/insertDeptLeaderFolderAuth")
    @GetUserInfo
    @Transactional
    @ApiOperation("给部门正副职分配某文件夹权限")
    public Object insertDeptLeaderFolderAuth(String entityIds, String level) {
        List<UsUser> users = userMapper.getAllUser();
        for(UsUser user: users){
            if(utilService.isDeptLeader(user.getAccount())) insertFolderAuth(entityIds, user.getAccount(), "1");
        }
        return ResultUtil.success();
    }

    @GetMapping("/insertStaffFolderAuth")
    @GetUserInfo
    @Transactional
    @ApiOperation("给员工分配文件夹权限")
    public Object insertFolderAuth(String entityIds, String account, String level) {
        String[] entityIdList = entityIds.split(",");
        UsUser user = new UsUser();
        user.setAccount(account);
        user = userService.getUser(user).get(0);
        String name = user.getName();
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        Authority authority;
        for(String entityId: entityIdList){
            authority = new Authority();
            authority.setAuthorityLevel(level);
            authority.setPermissionType("staff");
            authority.setPermissionId(account);
            authority.setPermissionName(name);
            authority.setCreateTime(time);
            authority.setUpdateTime(time);
            List<String> entityIds0 = authorityService.getChildrenAndMyself(entityId);
            for(String entityId2 : entityIds0){
                authority.setEntityId(entityId2);//部门文件夹
                authority.setEntityName(utilService.getEntityNameByEntityId(entityId2));
                authority.setId(authorityService.generateId());
                boolean result = authorityService.insertAuthority(authority);
                if(!result){
                    log.error("员工文件夹权限新增失败!");
                    throw new BusinessException("员工文件夹权限新增失败!");
                }
            }
        }
        return ResultUtil.success("员工文件夹权限新增成功!");
    }

    @GetMapping("/insertDeptOfficialFolderAuth")
    @GetUserInfo
    @Transactional
    @ApiOperation("给部门分配相应公司签批文件夹权限")
    public Object insertDeptOfficialFolderAuth() {
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        List<UsDept> depts = deptMapper.getAllDept();
        Authority authority = new Authority();
        authority.setAuthorityLevel("3");
        authority.setPermissionType("dept");
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        for(UsDept dept: depts){
            String name = dept.getOrganizationName();
            Folder folder = new Folder();
            folder.setEntityName(name);
            folder.setTag("签批文件");
            folder.setEntityRoom("0");
            authority.setPermissionId(dept.getOrganizationId());
            authority.setPermissionName(name);
            List<Folder> folders = folderMapper.getFolder(folder);
            for(Folder folder1 : folders){
                List<String> entityIds = authorityService.getChildrenAndMyself(folder1.getEntityId());
                for(String entityId : entityIds){
                    authority.setEntityId(entityId);//部门签批文件夹
                    authority.setEntityName(utilService.getEntityNameByEntityId(entityId));
                    authority.setId(authorityService.generateId());
                    boolean result = authorityService.insertAuthority(authority);
                    if(!result){
                        log.error("部门分配相应签批文件夹权限新增失败!");
                        throw new BusinessException("部门分配相应签批文件夹权限新增失败!");
                    }
                }
            }
        }
        return ResultUtil.success("部门分配相应签批文件夹权限新增成功!");
    }

    @GetMapping("/insertAuthName")
    @GetUserInfo
    @Transactional
    @ApiOperation("刷权限表文件名称")
    public Object insertAuthName() {
        Authority authority = new Authority();
        List<Authority> authorities = authorityMapper.getAuthority(authority);
        for(Authority authority1 : authorities){
            if(authority1.getEntityName() == null) authority1.setEntityName(utilService.getEntityNameByEntityId(authority1.getEntityId()));
            authorityMapper.updateAuthorityName(authority1);
        }
        return ResultUtil.success();
    }
}